package com.wanmait.gohome.controller.web;

import com.aliyuncs.exceptions.ClientException;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonArray;
import com.sun.org.apache.xpath.internal.operations.Mod;
import com.wanmait.gohome.pojo.*;
import com.wanmait.gohome.service.*;
import com.wanmait.gohome.util.AliyunMessageConfig;
import com.wanmait.gohome.util.CodeUtil;
import com.wanmait.gohome.util.CookieUtil;
import com.wanmait.gohome.util.Md5;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/web/userinfo")
public class UserinfoController {

    @Resource
    private UserinfoService userinfoService;
    @Resource
    private ProfessionService professionService;
    @Resource
    private AreaService areaService;
    @Resource
    private JournalService journalService;
    @Resource
    private AttentionService attentionService;
    @Resource
    private TaskService taskService;
    @Resource
    private InformationService informationService;
    @Resource
    private ConfigService configService;//信用表注入

    /**
     * 用户注册页面
     */
    @GetMapping("register")
    public void register1(){

    }

    /**
     * 用户注册提交
     */
    @PostMapping("register")
    @ResponseBody
    public void register2(Userinfo userinfo){
        userinfo.setPic("default.jpg");
        userinfoService.insertUser(userinfo);
    }

    /**
     * 用户登录页面
     */
    @GetMapping("login")
    public void login1(){

    }

    /**
     * 用户登录页面
     */
    @PostMapping("login")
    @ResponseBody
    public String login2(Userinfo userinfo, HttpSession session, String remenberMe, HttpServletResponse response, HttpServletRequest request){
        Userinfo userinfo1 = userinfoService.findByPhoneAndPass(userinfo);
        if(userinfo1==null){
            return "false";         //用户未注册
        }else{
            if(userinfo1.getEnable()){
                session.setAttribute("userinfo", userinfo1);
                Userinfo userinfo2 = new Userinfo();
                userinfo2.setId(userinfo1.getId());
                userinfo2.setIp(request.getRemoteAddr());
                userinfo2.setLoginCount(userinfo1.getLoginCount()+1);
                userinfo2.setLastLoginTime(new Date());
                userinfoService.updateById(userinfo2);

                if(remenberMe.equals("true")){
                    CookieUtil.addCookie("phone",userinfo.getPhone(),"/",60*60*24*30,response);
                    CookieUtil.addCookie("password", Md5.getSuperMD5(userinfo.getUserpass()),"/",60*60*24*30,response);
                    if(session.getAttribute("goUrl")!=null){
                        String url = (String)session.getAttribute("goUrl");
                        return url;
                    }else{
                        return "true";
                    }
                }else{
                    CookieUtil.addCookie("phone","","/",0,response);
                    CookieUtil.addCookie("password", "","/",0,response);
                    if(session.getAttribute("goUrl")!=null){
                        String url = (String)session.getAttribute("goUrl");
                        return url;
                    }else{
                        return "true";
                    }
                }

            }else{
                return "账户冻结";
            }
        }

    }


    /**
     *
     * @param session
     * @param response  用户注销
     * @return
     */
    @GetMapping("logout")
    public String logout(HttpSession session,HttpServletResponse response){
        session.removeAttribute("userinfo");
        CookieUtil.addCookie("phone","","/",0,response);
        CookieUtil.addCookie("password", "","/",0,response);
        return "redirect:/web/index";
    }


    /**
     *
     * @param phoneNum  检查手机号是否重复
     * @return
     */
    @GetMapping("checkPhone")
    @ResponseBody
    public String checkPhone(String phoneNum){
        String phone = userinfoService.selectByPhone(phoneNum);
        if(phone!=null&&phone.equals(phoneNum)){
            return "true";
        }
        return "false";
    }

    /**
     *
     * @param phone 注册 时 发送验证码    忘记密码时发送验证码
     * @return
     */
    @GetMapping("sendCode")
    @ResponseBody
    public String sendCode(String phone,HttpSession session,String edit){
        String code = CodeUtil.getCode();
        session.setAttribute("code",code);
        if(edit==null){
            edit="";
        }
        String msg="";
        try {
            msg =  AliyunMessageConfig.sendSms(phone,code,edit);
        } catch (ClientException e) {
        }
        if(msg!=""&& msg.equals("OK")) {
            return "true";
        }else{
            return "false";
        }
    }

    /**
     *
     * @param code  检查手机验证码是否正确
     * @return
     */
    @GetMapping("checkCode")
    @ResponseBody
    public String checkCode(String code,HttpSession session){
        String code1 = (String)session.getAttribute("code");

        if(code1!=null&&code1.equals(code)){
            return "true";
        }
        else{
            return "false";
        }
    }


    /**
     *   忘记密码第一页
     */
    @GetMapping("forgetPassword")
    public ModelAndView forgetPassword(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/web/userinfo/password_forget");
        return mv;
    }



    /**
     *   忘记密码 第二页    重设密码
     */
    @GetMapping("resetPassword")
    public ModelAndView resetPassword(String phone){
        ModelAndView mv = new ModelAndView();
        mv.addObject("phoneNum",phone);
        mv.setViewName("/web/userinfo/password_reset");
        String phoneNum = phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
        mv.addObject("phone",phoneNum);
        return mv;
    }


    /**
     *
     * @param userinfo   重设密码 第三页
     * @return
     */
    @PostMapping("resetPassword")
    public ModelAndView resetPassword1(Userinfo userinfo){
        ModelAndView mv = new ModelAndView();
        userinfoService.updateByPhone(userinfo);
        mv.setViewName("/web/userinfo/password_success");
        return mv;
    }


    /**
     *
     * @return 用户个人中心主页面
     */
    @GetMapping("index")
    public ModelAndView index(HttpServletRequest request)
    {
        ModelAndView mv = new ModelAndView();
        Userinfo userinfo = (Userinfo)request.getSession().getAttribute("userinfo");
        if(userinfo==null){
            request.getSession().setAttribute("goUrl",request.getRequestURI());
            mv.setViewName("/web/userinfo/login");
        }
        return mv;
    }

    /**
     *
     * @return 用户个人中心  首页统计展示
     */
    @GetMapping("homePage")
    public ModelAndView homePage(HttpSession session)
    {
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        ModelAndView mv = new ModelAndView();
        Integer journalCount = journalService.findCountByUserId(userinfo.getId());
        Integer taskCount = taskService.findCountByUserId(userinfo.getId());
        Integer attentionCount = attentionService.findCountByUserId(userinfo.getId());
        Integer InformationCount = informationService.findCountByUserId(userinfo.getId());
        mv.addObject("journalCount",journalCount);
        mv.addObject("taskCount",taskCount);
        mv.addObject("attentionCount",attentionCount);
        mv.addObject("InformationCount",InformationCount);
        return mv;
    }
    /**
     * 跳到申请成为志愿者页面,里面存放省市信息
     */
    @GetMapping("applyVolunteer")
    public ModelAndView applyVolunteer()
    {
        ModelAndView mv=new ModelAndView();
        List<Area> provinces = areaService.findCities(-1);
        mv.addObject("provinces",provinces);
        List<Profession> professions = professionService.findAll();
        mv.addObject("professions",professions);
        return mv;
    }


    /**
     *
     * @return   个人中心  基本信息
     */
    @GetMapping("details")
    public ModelAndView details(){
        ModelAndView mv = new ModelAndView();
        List<Profession> professions = professionService.findAll();
        List<Area> provinces = areaService.findCities(-1);
        mv.addObject("provinces",provinces);
        mv.addObject("professions",professions);
        return mv;
    }

    /**
     *
     * @param userinfo 个人中心  修改基本信息
     * @return
     */
    @PostMapping("details")
    public ModelAndView details1(Userinfo userinfo,HttpSession session)
    {
        Userinfo userinfo1 = userinfoService.findById(userinfo.getId());
        int credit=0;
        if(userinfo.getName()!= null&&userinfo1.getName()==null)
        {
            Config config = configService.findByConfigKey("name");//查询信用积分表所有东西
            credit = credit+Integer.parseInt(config.getConfigValue());
        }
        else if(userinfo.getUsername()!=null&&userinfo1.getUsername()==null)
        {
            Config config = configService.findByConfigKey("username");
            credit = credit+Integer.parseInt(config.getConfigValue());
        }
        else if(userinfo.getSex()!=null&&userinfo1.getSex()==null)
        {
            Config config = configService.findByConfigKey("sex");
            credit = credit+Integer.parseInt(config.getConfigValue());
        }
        else if(userinfo.getBirthday()!=null&&userinfo1.getBirthday()==null)
        {
            Config config = configService.findByConfigKey("birthday");
            credit = credit+Integer.parseInt(config.getConfigValue());
        }
        else if(userinfo.getEmail()!=null&&userinfo1.getEmail()==null)
        {
            Config config = configService.findByConfigKey("email");
            credit = credit+Integer.parseInt(config.getConfigValue());
        }
        else if(userinfo.getQq()!=null&&userinfo1.getQq()==null)
        {
            Config config = configService.findByConfigKey("qq");
            credit = credit+Integer.parseInt(config.getConfigValue());
        }
        else if(userinfo.getWechat()!=null&&userinfo1.getWechat()==null)
        {
            Config config = configService.findByConfigKey("wechat");
            credit = credit+Integer.parseInt(config.getConfigValue());
        }
        else if(userinfo.getRemark()!=null&&userinfo1.getRemark()==null)
        {
            Config config = configService.findByConfigKey("remark");
            credit = credit+Integer.parseInt(config.getConfigValue());
        }
        userinfo.setCredit(credit+userinfo1.getCredit());
        ModelAndView mv = new ModelAndView();
        userinfoService.updateByUserId(userinfo);
        Userinfo userinfo2 = userinfoService.findById(userinfo.getId());
        session.setAttribute("userinfo",userinfo2);
        mv.setViewName("/web/userinfo/homePage");
        return mv;
    }


    /**
     *   个人中心 修改密码页面
     */
    @GetMapping("editPassword")
    public void edit(){}


    /**
     *
     * @param userpass
     * @param session  个人中心修改密码 检查原密码是否正确
     * @return
     */
    @GetMapping("checkPass")
    @ResponseBody
    public String checkPass(String userpass,HttpSession session){
        Userinfo userinfo = (Userinfo) session.getAttribute("userinfo");
        System.out.println(userpass);
        if(userinfo.getUserpass().equals(userpass)){
            return "true";
        }else{
            return  "false";
        }
    }

    /**
     *
     * @param userinfo   个人中心 通过ID修改密码
     * @return
     */
    @PostMapping("editPassword")
    public String editPass(Userinfo userinfo){
        userinfoService.updateByUserId(userinfo);
        return "/web/userinfo/editPassword";
    }
    /**
     *   个人中心  修改头像页面
     */
    @GetMapping("editPic")
    public void editpic(){}


    /**
     *
     * @param request 个人中心 修改头像
     * @return
     */
    @PostMapping("editPic")
    @ResponseBody
    public String editPic2(HttpServletRequest request)
    {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        String fileName = "";
        List<MultipartFile> filelist = multipartRequest.getFiles("userlogo");
        for(MultipartFile file:filelist){
            if(!file.isEmpty()){
                String ext= FilenameUtils.getExtension(file.getOriginalFilename());
                fileName= UUID.randomUUID()+"."+ext;
                String path=request.getServletContext().getRealPath("/web/uploadImages/")+fileName;
                File outFile=new File(path);
                try{
                    file.transferTo(outFile);
                }catch(Exception e){}
                Userinfo userinfo1 = (Userinfo) request.getSession().getAttribute("userinfo");
                Userinfo userinfo = new Userinfo();
                userinfo.setId(userinfo1.getId());
                userinfo.setPic(fileName);
                userinfoService.updatePicById(userinfo);

                Userinfo userinfo2 = userinfoService.findById(userinfo1.getId());
                userinfo2.setLoginCount(userinfo1.getLoginCount());
                userinfo2.setIp(userinfo1.getIp());
                userinfo2.setLastLoginTime(userinfo1.getLastLoginTime());
                request.getSession().setAttribute("userinfo",userinfo2);
            }
        }
       return fileName;
    }

    /**
     *   个人中心  身份认证页面
     */
    @GetMapping("identity_prove")
    public void identity_prove(){}


    /**
     *
     * @param request
     * @param idCardPic
     * @param idCardVerso  个人中心  身份认证上传
     * @param id
     * @return
     */
    @PostMapping("identity_prove")
    public String  identity_prove1(HttpServletRequest request,MultipartFile idCardPic,MultipartFile idCardVerso,Integer id)
    {
        String ext= FilenameUtils.getExtension(idCardPic.getOriginalFilename());
        String ext1= FilenameUtils.getExtension(idCardVerso.getOriginalFilename());
        String fileName= UUID.randomUUID()+"."+ext;
        String fileName1= UUID.randomUUID()+"."+ext1;
        String path=request.getServletContext().getRealPath("/web/userinfo/img/uploadImages/")+fileName;
        String path1=request.getServletContext().getRealPath("/web/userinfo/img/uploadImages/")+fileName1;
        File outFile=new File(path);
        File outFile1=new File(path1);
        try{
            idCardPic.transferTo(outFile);
            idCardVerso.transferTo(outFile1);
        }catch(Exception e){
        }

        Userinfo userinfo = new Userinfo();
        userinfo.setId(id);
        userinfo.setIdCardPic(fileName);
        userinfo.setIdCardVerso(fileName1);
        userinfoService.updateByUserId(userinfo);
        userinfo = userinfoService.findById(userinfo.getId());
        Userinfo userinfo1 = (Userinfo)request.getSession().getAttribute("userinfo");
        userinfo1.setIdCardVerso(userinfo.getIdCardVerso());
        userinfo1.setIdCardPic(userinfo.getIdCardPic());
        request.getSession().setAttribute("userinfo",userinfo1);
        return "redirect:/web/userinfo/homePage";
    }

    /**
     * 申请成为志愿者
     * @param userinfo

     * @param request
     * @return
     */
    @PostMapping("applyVolunteer")
    public String applyVolunteer(Userinfo userinfo,HttpServletRequest request,String wechat)
    {
        userinfo.setApplyTime(new Timestamp(new Date().getTime()));
        userinfoService.updateApplyVolunteer(userinfo);
        return "redirect:/web/index";
    }


    /**
     *   个人中心    是否志愿者
     */
    @GetMapping("volunteer")
    public void volunteer(){
    }

    /**
     *  个人中心  我的关注
     */
    @GetMapping("attention")
    public void attention(){
    }

    /**
     *  个人中心  我的关注列表
     */
    @GetMapping("attentionList")
    @ResponseBody
    public ModelAndView attention(HttpSession session){
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        PageInfo<Attention> pageInfo = attentionService.findByUserId(userinfo.getId());
        ModelAndView mv = new ModelAndView();
        mv.addObject("pageInfo", pageInfo);
        return mv;
    }


    /**
     *   个人中心  我的日志
     */
    @GetMapping("log")
    public void log(){
    }

    /**
     *
     * @param session   个人中心  我的日志列表
     * @return
     */
    @GetMapping("logList")
    @ResponseBody
    public ModelAndView list(HttpSession session){
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        PageInfo<Journal> pageInfo = journalService.findByUserId(userinfo.getId());
        ModelAndView mv = new ModelAndView();
        mv.addObject("pageInfo", pageInfo);
        return mv;
    }


    /**
     *
     * @param journalId  个人中性 修改日志
     * @return
     */
    @GetMapping("updateByJournalId")
    public ModelAndView updateByJournalId(Integer journalId)
    {
        ModelAndView mv = new ModelAndView();
        Journal journal= journalService.findByIds(journalId);
        mv.addObject("journal",journal);
        mv.setViewName("/web/blogger/fabu");
        return mv;
    }

    /**
     *     个人中心  寻亲启事
     */
    @GetMapping("findPerson")
    public void findPerson(){

    }

    /**
     *
     * @param session   个人中心 发布的寻亲信息
     */
    @GetMapping("findPersonList")
    @ResponseBody
    public ModelAndView findPersonList(HttpSession session)
    {
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        PageInfo<Information> pageInfo = informationService.findByUserId(userinfo.getId());
        ModelAndView mv = new ModelAndView();
        mv.addObject("pageInfo", pageInfo);
        return mv;
    }

    /**
     *
     * @param informationId   个人中心  修改寻亲启事
     * @return
     */
    @GetMapping("updateByInformationId")
    public ModelAndView updateByInformationId(Integer informationId)
    {
        ModelAndView mv = new ModelAndView();
        Information information = informationService.findByInformation(informationId);
        List<Area> provinces = areaService.findCities(-1);
        mv.addObject("provinces",provinces);
        if(information.getLostTypeId()==1){
            mv.setViewName("/web/information/findPerson");
        }else if(information.getLostTypeId()==2){
            mv.setViewName("/web/information/findFamily");
        }else{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            int year = Integer.parseInt(sdf.format(new Date()));
            information.setAgeStart((year - Integer.parseInt(information.getAgeStart()))+"");
            information.setAgeEnd((year - Integer.parseInt(information.getAgeEnd()))+"");
            mv.setViewName("/web/information/findVolunteer");
        }
        mv.addObject("information",information);
        return mv;
    }

    /**
     *   个人中心  任务管理
     */
    @GetMapping("task")
    public void task(){
    }

    /**
     *
     * @param session   个人中心 查看发布任务
     * @return
     */
    @GetMapping("taskList")
    @ResponseBody
    public ModelAndView taskList(HttpSession session)
    {
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        PageInfo<Task> pageInfo = taskService.findByUserId(userinfo.getId());
        ModelAndView mv = new ModelAndView();
        mv.addObject("pageInfo", pageInfo);
        return mv;
    }

    /**
     *
     * @param taskId   个人中心  对未审核和未通过的任务进行修改
     * @return
     */
    @GetMapping("updateByTaskId")
    public ModelAndView updateByTaskId(Integer taskId)
    {
        ModelAndView mv = new ModelAndView();
        Task task = taskService.findById(taskId);
        mv.addObject("task",task);
        mv.setViewName("/web/task/publishTask");
        return mv;
    }

    /**
     *   个人中心  任务管理 接受的任务
     */
    @GetMapping("acceptTask")
    public void acceptTask(){
    }


    /**
     *
     * @param session   个人中心 查看接收的任务
     * @return
     */
    @GetMapping("acceptTaskList")
    @ResponseBody
    public ModelAndView acceptTaskList(HttpSession session)
    {
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        PageInfo<Task> pageInfo = taskService.selectByUserId(userinfo.getId());
        ModelAndView mv = new ModelAndView();
        mv.addObject("pageInfo", pageInfo);
        return mv;
    }

    /**
     *   个人中心 完成任务 页面
     */
    @GetMapping("finishTask")
    public void finishTask() { }

    /**
     *   个人中心  完成任务列表
     */
    @GetMapping("finishTaskList")
    @ResponseBody
    public ModelAndView finishTaskList(HttpSession session)
    {
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        PageInfo<Task> pageInfo = taskService.selectFinishByUserId(userinfo.getId());
        ModelAndView mv = new ModelAndView();
        mv.addObject("pageInfo", pageInfo);
        return mv;
    }

    /**
     *
     * @param informationId   个人中心  取消关注
     */
    @GetMapping("deleteAttentionById")
    @ResponseBody
    public void deleteAttentionById(String informationId,HttpSession session){
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        Integer id = Integer.parseInt(informationId);
        attentionService.deleteByUserIdAndInformationId(userinfo.getId(),id);
    }

    /**
     *
     * @param journalId  个人中心  删除日志
     */
    @GetMapping("deleteByJournalId")
    @ResponseBody
    public void deleteByJournalId(String journalId)
    {
        Integer id = Integer.parseInt(journalId);
        journalService.deleteByJournalId(id);
    }


    /**
     *
     * @param taskId   个人中心  删除任务
     */
    @GetMapping("deleteByTaskId")
    @ResponseBody
    public void deleteByTaskId(String taskId)
    {
        Integer id = Integer.parseInt(taskId);
        taskService.deleteByTaskId(id);
    }

    /**
     *
     * @param informationId   个人中心  删除寻亲启事
     */
    @GetMapping("deleteByInformationId")
    @ResponseBody
    public void deleteByInformationId(String informationId)
    {
        Integer id = Integer.parseInt(informationId);
        informationService.deleteByInformationId(id);
    }


    /**
     *
     * @param session 个人中心放弃任务
     */
    @GetMapping("giveUpByTaskId")
    @ResponseBody
    public void giveUpByTaskId(HttpSession session,String taskId)
    {
        Integer id = Integer.parseInt(taskId);
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        userinfoService.giveUpByTaskId(userinfo.getId(),id);
    }

    /**
     *
     * @param session 个人中心完成任务
     */
    @GetMapping("finishByTaskId")
    @ResponseBody
    public void finishByTaskId(HttpSession session,Integer taskId,String finishReason)
    {
        System.out.println(finishReason);
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        userinfoService.finishByTaskId(userinfo.getId(),taskId,finishReason);
    }



}
